package com.tongcao.cn.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.ui.ModelMap;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

/**
 * <pre>
 *    author  : Booker
 *    time    : 2017/12/12 16:12
 *    desc    : ModelMapUtils
 *    version : v1.0
 * </pre>
 */
public class ModelMapUtils {

    /**
     * @param modelMap
     * @param obj
     */
    public static void convertToModelMap(ModelMap modelMap, Object obj) {
        convertToModelMap(modelMap, obj, null);
    }

    /**
     * @param modelMap
     * @param obj
     * @param ignoreFields 忽略的属性
     */
    public static void convertToModelMap(ModelMap modelMap, Object obj, String... ignoreFields) {
        List<String> ignoreFieldList = ignoreFields == null ? null : Arrays.asList(ignoreFields);
        Field[] fields = obj.getClass().getFields();
        for (Field field : fields) {
            String fieldName = field.getName();
            if (ignoreFieldList != null && !ignoreFieldList.contains(fieldName)) {
                continue;
            } else {
                modelMap.put(fieldName, getFieldValueByName(fieldName, obj));
            }
        }
    }

    /**
     * 根据属性名获取属性值
     *
     * @param fieldName
     * @param obj
     * @return
     */
    public static Object getFieldValueByName(String fieldName, Object obj) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = obj.getClass().getMethod(getter, new Class[]{});
            Object value = method.invoke(obj, new Object[]{});
//            if (null == value && method.getReturnType().getName().equals("java.lang.String")) {
            if (null == value && method.getReturnType().getName() instanceof String) {
                return StringUtils.EMPTY;
            }
            return value;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
